package cn.itcast.bos.web.action;

import java.io.IOException;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.Staff;
import cn.itcast.bos.utils.PageBean;
import cn.itcast.bos.web.action.base.BaseAction;

/**
 * 取派员管理Action
 * @author zhaoqx
 *
 */
@Controller
@Scope("prototype")
public class StaffAction extends BaseAction<Staff>{
	/**
	 * 保存取派员
	 */
	public String save(){
		//System.out.println(model);
		staffService.save(model);
		return "list";
	}
	
	
	public int getPage() {
		return page;
	}

	
	public int getRows() {
		return rows;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	private int page;//属性驱动，当前页码
	private int rows;//属性驱动，每页显示的记录数
	
	/**
	 * 查询取派员数据，序列化为json返回
	 * @throws IOException 
	 */
	public String pageQuery() throws IOException{
		PageBean pageBean = new PageBean();
		pageBean.setCurrentPage(page);//当前页码
		pageBean.setPageSize(rows);//每页显示的记录数
		
		//使用离线条件查询对象包装查询条件
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Staff.class);
		pageBean.setDetachedCriteria(detachedCriteria);
		
		//调用Service完成分页查询
		staffService.pageQuery(pageBean);
		
		//PageBean对象中的list和total都有值了
		
		//使用json-lib将PageBean对象序列化为json数据返回
		
		//使用JsonConfig对象设置哪些属性不需要进行序列化
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(new String[]{"detachedCriteria","pageSize","currentPage"});
		JSONObject jsonObject = JSONObject.fromObject(pageBean,jsonConfig);
		String json = jsonObject.toString();
		
		//将json数据通过输出流写到客户端
		ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
		ServletActionContext.getResponse().getWriter().print(json);
		return NONE;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	//接收作废方法传递的参数
	private String ids;
	/**
	 * 作废方法
	 */
	public String delete(){
		staffService.delete(ids);
		return "list";
	}
	
	/**
	 * 修改取派员信息
	 */
	public String update(){
		//先查询原始数据，再进行数据覆盖
		Staff staff = staffService.findById(model.getId());
		//进行覆盖
		staff.setName(model.getName());
		staff.setTelephone(model.getTelephone());
		staff.setStation(model.getStation());
		if(model.getHaspda() != null){
			staff.setHaspda(model.getHaspda());
		}else{
			staff.setHaspda("0");
		}
		staff.setStandard(model.getStandard());
		staffService.update(staff);
		return "list";
	}
}
